import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class HuffmanTree {
    public static void main(String[] args) {
        int[] array = {13,7,8,3,29,6,1};
        Node root = creatHuffmanTree(array);
        preOrder(root);
    }

    /**
     * 创建哈夫曼树
     * @param array:待排序数组
     * @return:树顶值
     */
    public static Node creatHuffmanTree(int[] array){
        List<Node> nodes = new ArrayList<Node>();

        for(int value : array){
            nodes.add(new Node(value));
        }

        //将node从小到大排序
        //注意这里是Collections
        Collections.sort(nodes);

        System.out.println("node = " + nodes);

        while(nodes.size() > 1) {
            //最小值节点
            Node leftNode = nodes.get(0);
            //第二小值得节点
            Node rightNode = nodes.get(1);
            //构建最新一个二叉树
            Node parent = new Node(leftNode.value + rightNode.value);
            parent.left = leftNode;
            parent.right = rightNode;
            //删除叶子结点
            nodes.remove(leftNode);
            nodes.remove(rightNode);
            //parent加入到nodes中
            nodes.add(parent);

            System.out.println("第一次处理：" + nodes);
        }
        return nodes.get(0);
    }

    public static void preOrder(Node root){
        if(root != null){
            root.preOrder();
        }else{
            System.out.println("根节点为空");
        }
    }

}

class Node implements Comparable<Node>{
    int value;
    Node left;
    Node right;

    public Node(int value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return "Node{" +
                "value=" + value +
                '}';
    }

    @Override
    public int compareTo(Node o) {
        //从小到大排序
        return this.value - o.value;
    }

    public void preOrder(){
        System.out.println(this);
        if(this.left != null){
            this.left.preOrder();
        }
        if(this.right != null){
            this.right.preOrder();
        }
    }
}

